package edu.algorithm.knn.parallel.common;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import edu.algorithm.knn.parallel.exception.ParrallelKNNException;

/**
 * 读取数据和对应的标签
 * @author liukun
 *
 */
public class FileOperator {

	private String dataFilePath;
	private String labelFilePath;

	private BufferedReader dataReader;
	private BufferedReader labelReader;

	private String dataNextLine;
	private String lableNextLine;

	public FileOperator(String dataFilePath, String labelFilePath) throws FileNotFoundException {
		this.dataFilePath = dataFilePath;
		this.labelFilePath = labelFilePath;
		init();
	}

	private void init() throws FileNotFoundException {
		FileReader dataReader;
		try {
			dataReader = new FileReader(dataFilePath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw e;
		}
		FileReader labelReader;
		try {
			labelReader = new FileReader(labelFilePath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw e;
		}
		this.dataReader = new BufferedReader(dataReader);
		this.labelReader = new BufferedReader(labelReader);
	}

	public boolean hasData() throws ParrallelKNNException {

		try {
			dataNextLine = dataReader.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			lableNextLine = labelReader.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (dataNextLine == null && lableNextLine != null) {
			throw new ParrallelKNNException("No data, but has label");
		} else if (dataNextLine != null && lableNextLine == null) {
			throw new ParrallelKNNException("No label, but has data");
		}

		return dataNextLine != null && lableNextLine != null;
	}

	public String[] next() {

		String[] res = new String[2];
		res[0] = dataNextLine;
		res[1] = lableNextLine;

		return res;
	}

}
